package org.itzheng.yuezhi.real.tools.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import org.itzheng.yuezhi.R;
import org.itzheng.yuezhi.adapter.BaseRecyclerViewAdapter;
import org.itzheng.yuezhi.adapter.BluetoothListRcvAdapter;
import org.itzheng.yuezhi.base.BaseActivity;
import org.itzheng.yuezhi.utils.comm.BlueToothBroadcastReceiverUtils;
import org.itzheng.yuezhi.utils.comm.BlueToothUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by admin on 2017/8/7.
 */

public class SearchBluetoothActivity extends BaseActivity {
    List<BluetoothDevice> bondBluetooth = new ArrayList<>();
    List<BluetoothDevice> noBondBluetooth = new ArrayList<>();
    BluetoothListRcvAdapter bondAdapter;
    BluetoothListRcvAdapter noBondAdapter;
    @BindView(R.id.rcvBondBluetooth)
    RecyclerView rcvBondBluetooth;
    @BindView(R.id.rcvNoBondBluetooth)
    RecyclerView rcvNoBondBluetooth;
    private static final String TAG = "SearchBluetoothActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("搜索蓝牙");
        setContentView(R.layout.activity_search_bluetooth);
        ButterKnife.bind(this);
        BlueToothBroadcastReceiverUtils.getInstance(this).registerReceiver();
        BlueToothBroadcastReceiverUtils.getInstance(this).restartDiscovery();
        BlueToothBroadcastReceiverUtils.getInstance(this).addOnSearchBluetoothListener(new BlueToothBroadcastReceiverUtils.OnSearchBluetoothListener() {
            @Override
            public void discoveryStart() {
                Log.d(TAG, "discoveryStart");
            }

            @Override
            public void discoveryFinish() {
                Log.d(TAG, "discoveryFinish");
            }

            @Override
            public void foundBonded(BluetoothDevice device) {
                bondBluetooth.add(device);
                setBondAdapter();
            }

            @Override
            public void foundNoBond(BluetoothDevice device) {
                noBondBluetooth.add(device);
                setNoBondAdapter();
            }
        });
//        initIntentFilter();
//        doDiscovery();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BlueToothBroadcastReceiverUtils.removeInstance(this);
    }

    /**
     * 开始服务和设备查找
     */
    private void doDiscovery() {
        // 关闭再进行的服务查找
        if (BlueToothUtils.isDiscovering()) {
            BlueToothUtils.cancelDiscovery();
        }
        //并重新开始
        BlueToothUtils.startDiscovery();
    }

    private void initIntentFilter() {
        // 注册接收查找到设备action接收器
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, filter);
        // 注册查找结束action接收器
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, filter);
    }

    // 查找到设备和搜索完成action监听器
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // 查找到设备action
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // 得到蓝牙设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 如果是已配对的则略过，已得到显示，其余的在添加到列表中进行显示
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    noBondBluetooth.add(device);
                    setNoBondAdapter();
                } else {  //添加到已配对设备列表
                    bondBluetooth.add(device);
                    setBondAdapter();
                }
                // 搜索完成action
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                setTitle("选择要连接的设备");

            }
        }
    };

    private void setNoBondAdapter() {
        if (noBondAdapter == null) {
            noBondAdapter = new BluetoothListRcvAdapter(noBondBluetooth);
            noBondAdapter.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener() {
                @Override
                public void OnItemClick(View view, int position) {
                    BluetoothDevice device = noBondBluetooth.get(position);
                    finishAndSetResult(device);
                }
            });
            rcvNoBondBluetooth.setLayoutManager(new LinearLayoutManager(this));
            rcvNoBondBluetooth.setAdapter(noBondAdapter);
        } else {
            noBondAdapter.notifyDataSetChanged();
        }
    }

    private void setBondAdapter() {
        if (bondAdapter == null) {
            bondAdapter = new BluetoothListRcvAdapter(bondBluetooth);
            bondAdapter.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener() {
                @Override
                public void OnItemClick(View view, int position) {
                    BluetoothDevice device = bondBluetooth.get(position);
                    finishAndSetResult(device);
                }
            });
            rcvBondBluetooth.setLayoutManager(new LinearLayoutManager(this));
            rcvBondBluetooth.setAdapter(bondAdapter);
        } else {
            bondAdapter.notifyDataSetChanged();
        }
    }

    public static final String EXTRA_BLUETOOTH_DEVICE = "SearchBluetoothActivity";

    private void finishAndSetResult(BluetoothDevice device) {
        Intent intent = new Intent();
        intent.putExtra(EXTRA_BLUETOOTH_DEVICE, device);
        setResult(RESULT_OK, intent);
        finish();
    }
}
